#include "event_loop.h"
#include "logger.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void *event_loop_thread(void *arg) {
    event_loop_t *loop = (event_loop_t *)arg;
    event_queue_node_t *node = NULL;

    LOG_INFO("Event loop '%s' started", loop->name);

    while (loop->running) {
        pthread_mutex_lock(&loop->queue.mutex);

        // 等待事件到来
        while (loop->queue.size == 0 && loop->running) {
            pthread_cond_wait(&loop->queue.cond, &loop->queue.mutex);
        }

        if (!loop->running) {
            pthread_mutex_unlock(&loop->queue.mutex);
            break;
        }

        // 取出事件
        node = loop->queue.head;
        if (node) {
            loop->queue.head = node->next;
            if (loop->queue.tail == node) {
                loop->queue.tail = NULL;
            }
            loop->queue.size--;
        }
        pthread_mutex_unlock(&loop->queue.mutex);

        if (node) {
            event_t *event = &node->event;

            // 处理事件
            if (event->type < MAX_EVENT_TYPES && loop->handlers[event->type] != NULL) {
                loop->handlers[event->type](event);
            } else {
                LOG_WARN("No handler registered for event type: %d", event->type);
            }

            // 清理事件
            if (event->cleanup_fn) {
                event->cleanup_fn(event->data);
            }

            free(node);
        }
    }

    LOG_INFO("Event loop '%s' stopped", loop->name);
    return NULL;
}

int event_loop_init(event_loop_t *loop, const char *name, size_t max_size) {
    if (!loop || !name) {
        return ERROR_INVALID_PARAM;
    }

    memset(loop, 0, sizeof(event_loop_t));

    // 初始化队列
    loop->queue.head = NULL;
    loop->queue.tail = NULL;
    loop->queue.size = 0;
    loop->queue.max_size = max_size > 0 ? max_size : MAX_EVENTS;

    if (pthread_mutex_init(&loop->queue.mutex, NULL) != 0) {
        return ERROR_THREAD_CREATE;
    }

    if (pthread_cond_init(&loop->queue.cond, NULL) != 0) {
        pthread_mutex_destroy(&loop->queue.mutex);
        return ERROR_THREAD_CREATE;
    }

    // 初始化其他字段
    loop->name = strdup(name);
    loop->running = false;
    memset(loop->handlers, 0, sizeof(loop->handlers));

    return SUCCESS;
}

int event_loop_register_handler(event_loop_t *loop, event_type_t type, event_handler_t handler) {
    if (!loop || type >= MAX_EVENT_TYPES) {
        return ERROR_INVALID_PARAM;
    }

    loop->handlers[type] = handler;
    return SUCCESS;
}

int event_loop_send_event(event_loop_t *loop, event_t *event) {
    if (!loop || !event) {
        return ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&loop->queue.mutex);

    if (loop->queue.size >= loop->queue.max_size) {
        pthread_mutex_unlock(&loop->queue.mutex);
        return ERROR_QUEUE_FULL;
    }

    // 创建队列节点
    event_queue_node_t *node = malloc(sizeof(event_queue_node_t));
    if (!node) {
        pthread_mutex_unlock(&loop->queue.mutex);
        return ERROR_MEMORY_ALLOC;
    }

    // 复制事件（浅拷贝，数据指针不复制）
    memcpy(&node->event, event, sizeof(event_t));
    node->next = NULL;

    // 添加到队列
    if (loop->queue.tail) {
        loop->queue.tail->next = node;
    } else {
        loop->queue.head = node;
    }
    loop->queue.tail = node;
    loop->queue.size++;

    pthread_cond_signal(&loop->queue.cond);
    pthread_mutex_unlock(&loop->queue.mutex);

    return SUCCESS;
}

int event_loop_start(event_loop_t *loop) {
    if (!loop) {
        return ERROR_INVALID_PARAM;
    }

    if (loop->running) {
        LOG_WARN("Event loop '%s' is already running", loop->name);
        return SUCCESS;
    }

    loop->running = true;

    if (pthread_create(&loop->thread, NULL, event_loop_thread, loop) != 0) {
        loop->running = false;
        return ERROR_THREAD_CREATE;
    }

    return SUCCESS;
}

void event_loop_stop(event_loop_t *loop) {
    if (!loop || !loop->running) {
        return;
    }

    loop->running = false;

    // 通知等待的线程
    pthread_cond_broadcast(&loop->queue.cond);

    // 等待线程结束
    pthread_join(loop->thread, NULL);
}

void event_loop_cleanup(event_loop_t *loop) {
    if (!loop) {
        return;
    }

    event_loop_stop(loop);

    // 清理队列中剩余的事件
    pthread_mutex_lock(&loop->queue.mutex);
    event_queue_node_t *node = loop->queue.head;
    while (node) {
        event_queue_node_t *next = node->next;
        if (node->event.cleanup_fn) {
            node->event.cleanup_fn(node->event.data);
        }
        free(node);
        node = next;
    }
    pthread_mutex_unlock(&loop->queue.mutex);

    pthread_mutex_destroy(&loop->queue.mutex);
    pthread_cond_destroy(&loop->queue.cond);

    if (loop->name) {
        free(loop->name);
    }
}

event_t *event_create(event_type_t type, void *data, size_t data_len, void (*cleanup_fn)(void*)) {
    event_t *event = malloc(sizeof(event_t));
    if (!event) {
        return NULL;
    }

    event->type = type;
    event->data = data;
    event->data_len = data_len;
    event->source = NULL;
    event->cleanup_fn = cleanup_fn;

    return event;
}

void event_destroy(event_t *event) {
    if (event) {
        if (event->source) {
            free(event->source);
        }
        free(event);
    }
}
